package com.aishua.aishuawallet.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.Toast;

import com.aishua.aishuawallet.Constant;
import com.aishua.aishuawallet.R;
import com.aishua.aishuawallet.bean.ResAuthBean;
import com.aishua.aishuawallet.bean.TokenInfo;
import com.aishua.aishuawallet.business.TaskBusiness;
import com.aishua.aishuawallet.longconnection.SocketFactory;
import com.aishua.aishuawallet.mina.MianManager;
import com.aishua.aishuawallet.mina.MinaResultLIstener;
import com.aishua.aishuawallet.utils.AndroidUtils;
import com.aishua.aishuawallet.utils.CacheUtils;
import com.aishua.aishuawallet.utils.LogUtils;

import org.apache.mina.core.session.IoSession;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by aishua on 2018/8/1.
 */

public class WelcomeActivity extends BaseActivity {

    private static final String TAG = "WelcomeActivity-";
    private ImageView img_wecome;
    private Context mContext;
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {

                case 3:

                    Bundle bundle = msg.getData();

                    String authtype = (String) bundle.get(Constant.AUTH_TYPE);
                    ResAuthBean resAuthBean = (ResAuthBean) bundle.getSerializable("resAuthBean");
                    successLogin(authtype, resAuthBean);

                    break;
                case 4:

                    Toast.makeText(mContext, getResources().getString(R.string.loginfail), Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(WelcomeActivity.this, LoginActivity.class);
                    startActivity(intent);
                    finish();
                    break;
                case 5:

                    CreatWallet();
                    break;
            }

        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceStat) {
        super.onCreate(savedInstanceStat);
        setContentView(R.layout.activity_welcome);
        mContext = this;
        initView();
        initData();

    }

    private void initView() {

        img_wecome = findViewById(R.id.img_wecome);
    }

    private void initData() {

        img_wecome.setBackground(getResources().getDrawable(R.drawable.a));
        setAnimation();

    }

    private void setAnimation() {

        //渐变
        AlphaAnimation aa = new AlphaAnimation(0, 1);
        aa.setFillAfter(true);

        //缩放
        ScaleAnimation sa = new ScaleAnimation(0, 1, 0, 1, ScaleAnimation.RELATIVE_TO_SELF, 0.5f, ScaleAnimation.RELATIVE_TO_SELF, 0.5f);
        sa.setFillAfter(true);

        AnimationSet set = new AnimationSet(false);

        //添加动画，1500ms
        set.addAnimation(aa);
        set.addAnimation(sa);
        set.setDuration(1500);

        img_wecome.startAnimation(set);

        set.setAnimationListener(new GuideAnimationListener());
    }

    private class GuideAnimationListener implements Animation.AnimationListener {
        //动画开始播放时回调
        @Override
        public void onAnimationStart(Animation animation) {

        }

        //动画播放结束时回调
        @Override
        public void onAnimationEnd(Animation animation) {


            gotoActivity();
        }

        //动画重复播放时回调
        @Override
        public void onAnimationRepeat(Animation animation) {


        }
    }

    private void gotoActivity() {

        Intent intent = null;
        //判断是否进过主界面
        String phone = CacheUtils.getLoginname(this, Constant.PHONE);
        String pw = CacheUtils.getLogipw(this, Constant.PW);
        LogUtils.v(TAG + "pw:" + pw + "-phone:" + phone);

        if (null != pw && null != phone) {

            login(phone, pw);

        } else {

            boolean isStartMain = CacheUtils.getBoolean(WelcomeActivity.this, Constant.ISMAIN);
//            isStartMain 改为true开发好调试
            if (isStartMain) {
                //进过---主界面
                intent = new Intent(WelcomeActivity.this, LoginActivity.class);
            } else {
                //没进过---引导界面
                intent = new Intent(WelcomeActivity.this, GuideActivity.class);
            }
            startActivity(intent);
            finish();
        }

    }

    private void login(final String phone, final String pw) {

        TaskBusiness.getInstance().doAuth(mContext, "02", "2020", phone, pw,
                new MinaResultLIstener() {
                    @Override
                    public void messageReceived(IoSession session, Object msg) {

                        MianManager.getManager().shutDown();
                        LogUtils.v(TAG + "resultConten:" + msg.toString());
                        Message message = Message.obtain();
                        Bundle bundle = new Bundle();
                        bundle.putString(Constant.AUTH_TYPE, "02");
                        String msg1 = msg.toString();
                        String result = msg1.substring(74, 76);
                        LogUtils.v(TAG + "result:" + result);

                        String iccid = msg1.substring(76, 96);
                        String cardkey = msg1.substring(96, 352);
                        String tokennum = msg1.substring(352, 354);
                        int tokenlen = 0;
                        LogUtils.v(TAG + "tokennum：" + tokennum);
                        if (result.equals("00")) {

                            if (Integer.valueOf(tokennum) > 0) {

                                ResAuthBean resAuthBean = new ResAuthBean();
                                List<TokenInfo> tokenInfos = new ArrayList<>();
                                for (int i = 0; i < Integer.valueOf(tokennum); i++) {

                                    int tokenlenindex = Integer.parseInt(msg1.substring(354, 358), 16);
                                    LogUtils.v(TAG+"tokenlenindex:"+tokenlenindex);
                                    String tokenid = msg1.substring(358 + tokenlen, 374 + tokenlen);
                                    LogUtils.v(TAG+"tokenid:"+tokenid);
                                    String tokennamelen = msg1.substring(374 + tokenlen, 376 + tokenlen);
                                    LogUtils.v(TAG+"tokennamelen:"+tokennamelen);
                                    int tokennamelenint = Integer.parseInt(tokennamelen, 16);
                                    LogUtils.v(TAG+"tokennamelenint:"+tokennamelenint);
                                    String tokename = msg1.substring(376 + tokenlen, 376 + tokenlen + tokennamelenint);
                                    LogUtils.v(TAG+"tokename:"+AndroidUtils.unicode2String(tokename));
                                    String tokenaddr = msg1.substring(376 + tokenlen + tokennamelenint, 416 + tokenlen + tokennamelenint);
                                    LogUtils.v(TAG+"tokenaddr:"+tokenaddr);
                                    String cointype = msg1.substring(416 + tokenlen + tokennamelenint, 424 + tokenlen + tokennamelenint);
                                    LogUtils.v(TAG+"cointype:"+cointype);
                                    LogUtils.v(TAG + "tokenlenindex：" + tokenlenindex + "tokenid:" + tokenid + "tokename:" + tokename + "tokenaddr:" + tokenaddr + "cointype:" + cointype);

                                    TokenInfo tokenInfo = new TokenInfo();
                                    tokenInfo.setTokenID(tokenid);
                                    tokenInfo.setTokenName(AndroidUtils.unicode2String(tokename));
                                    tokenInfo.setTokenAddr(tokenaddr);
                                    tokenInfo.setCoinType(cointype);

                                    tokenlen = tokenlenindex;

                                    tokenInfos.add(tokenInfo);
                                    resAuthBean.setTokenNum(tokennum);
                                    resAuthBean.setTokenInfo(tokenInfos);
                                }
                                bundle.putSerializable("resAuthBean", resAuthBean);
                                message.what = Constant.SUCCESS_LOGIN;

                            } else {

//
                                message.what = Constant.CREAT_WALLET;
                            }
                        } else {

                            message.what = Constant.FAIL_LOGIN;
                        }

                        message.setData(bundle);
                        mHandler.sendMessage(message);

                    }

                    @Override
                    public void exceptionCaught(IoSession session, Throwable cause) {

                        LogUtils.v(TAG + "failmsg:" + cause.getMessage());

                    }
                }
        );

//        Message message = Message.obtain();
//        Bundle bundle = new Bundle();
//        ResAuthBean resAuthBean = new ResAuthBean();
//        TokenInfo tokenInfo = new TokenInfo();
//        List<TokenInfo> tokenInfos = new ArrayList<>();
//        resAuthBean.setTokenNum("1");
//        resAuthBean.setClientID("1111111111111");
//        resAuthBean.setCardKey("111111111111111111111111");
//        resAuthBean.setResult("00");
//        resAuthBean.setTokenNum("01");
//
//        tokenInfo.setCoinType("01");
//        tokenInfo.setTokenAddr("1111111111111111111111111111111111111111");
//        tokenInfo.setTokenName("111111111111");
//        tokenInfo.setTokenID("1111111111111111");
//        tokenInfos.add(tokenInfo);
//        resAuthBean.setTokenInfo(tokenInfos);
//        bundle.putSerializable("resAuthBean", resAuthBean);
//        message.what = Constant.SUCCESS_LOGIN;
//        bundle.putString("tokennum", "01");
//
//        message.setData(bundle);
//       mHandler.sendMessage(message);
    }

    private void successLogin(String authtype, ResAuthBean resAuthBean) {


        Toast.makeText(mContext, getResources().getString(R.string.loginsuccess), Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
        intent.putExtra("resAuthBean", resAuthBean);
        startActivity(intent);
        finish();

    }

    private void CreatWallet() {

        Intent intent = new Intent(WelcomeActivity.this, CreatWalletActivity.class);
        startActivity(intent);
        finish();

    }

}




